import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import rehypePrettyCode from "rehype-pretty-code";
import { ReactNode } from "react";
import CopyIcon from "../CopyIcon";

/**
 * 复制单行内容到粘贴板
 * content : 需要复制的内容
 * message : 复制完后的提示，不传则默认提示"复制成功"
 */
function copyToClip(content, message) {
  var aux = document.createElement("input");
  aux.setAttribute("value", content);
  document.body.appendChild(aux);
  aux.select();
  document.execCommand("copy");
  document.body.removeChild(aux);
  if (message == null) {
    alert("复制成功");
  } else {
    alert(message);
  }
}

export default async function Code({ code }: { code: ReactNode }) {
  // 这里可以添加自定义的代码高亮逻辑
  // 例如使用 highlight.js 库来高亮代码
  console.log(code);
  const { className, children } = code.props;
  //   console.log(className, children);
  const language = className?.replace(/language-/, "");
  const codeString = `
  ~~~${language}
${children}~~~`;
  const content = await unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypePrettyCode, {
      keepBackground: false,
    })
    .use(rehypeStringify)
    .process(codeString);
  const htmlContent = content.value;
  return (
    <div style={{ position: "relative" }}>
      <div
        style={{
          backgroundColor: "black",
          borderRadius: "4px",
          padding: "6px 16px",
          lineHeight: "1.5rem",
          margin: "10px 0",
          position: "relative",
        }}
        //   <div></div>
        dangerouslySetInnerHTML={{ __html: htmlContent }}
      />
      <CopyIcon
        text={children}
        style={{
          position: "absolute",
          top: "4px",
          right: "6px",
          cursor: "pointer",
        }}
      />
    </div>
  );
}
